package com.xiaomo.gitee.datamanager.security.handler;

import com.xiaomo.gitee.datamanager.common.result.Code;
import com.xiaomo.gitee.datamanager.common.result.Result;
import com.xiaomo.gitee.datamanager.util.HttpUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import java.io.IOException;

public class LoginFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        String code;
        System.out.println(exception.getClass());
        if (exception instanceof BadCredentialsException) {
            code = Code.LOGIN_FAILED_INCORRECT_PASSWORD;
        } else {
            code = Code.UNKNOWN_ERROR;
        }
        HttpUtils.writeJson(response, Result.fail(Integer.parseInt(code),Code.getInfo(code)));
    }
}
